package yto.freemarker.java8.lambda;

import javafx.scene.media.SubtitleTrack;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * 测试Lambda的内置的四大核心函数式接口
 * <p>
 * consumer   消费型接口
 * <p>
 * void accept(T e)
 * <p>
 * Supplier   供给型接口
 * <p>
 * T get()
 * <p>
 * Function<T,R>  函数型接口
 * R get(T t)
 * <p>
 * Predicate<T>  断言型接口
 * <p>
 * boolean  test(T t)
 *
 * @author dongxing
 * @create 2018-06-19 13:35
 **/
public class LambdaDemo2 {


    /**
     * 消费型接口
     */
    @Test
    public void test1() {
        happy(1000.0, (m) -> System.out.println("每次消费：" + m));
    }

    private void happy(Double money, Consumer<Double> consumer) {
        consumer.accept(money);

    }

    /**
     * 供给型接口
     */
    @Test
    public void test2() {
        List<Integer> numList = getNumList(10, () -> {
            return (int) (Math.random() * 100);
        });

        for (Integer integer : numList) {
            System.out.println(integer);
        }
    }

    private List<Integer> getNumList(int num, Supplier<Integer> supplier) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            list.add(supplier.get());
        }
        return list;

    }

    /**
     * 函数型接口
     */
    @Test
    public void test3() {
        String s = strHandler("\t\t\t   你好世界  ", (e) -> e.trim());
        System.out.println(s);

    }

    private String strHandler(String str, Function<String, String> function) {
        return function.apply(str);

    }

    /**
     * 断言型接口
     * 将满足条件的字符串放入到集合中
     */
    @Test
    public void test4() {
        List<String> list = Arrays.asList("hello", "nihao", "mingtian", "haha");

        List<String> filter = filter(list, s -> {
            return s.length() > 3;
        });
        for (String s : filter) {
            System.out.println(s);
        }

    }

    private List<String> filter(List<String> list, Predicate<String> predicate) {
        List<String> list1 = new ArrayList<>();
        for (String s : list) {
            if (predicate.test(s)) {
                list1.add(s);
            }
        }
        return list1;

    }
}
